package ch.dungegondefenders.appstates;

import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Shape;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import ch.dungegondefenders.DFConsts;
import ch.dungegondefenders.playfield.ExamplePlayField;
import ch.dungegondefenders.playfield.Field;
import ch.dungegondefenders.playfield.PlayField;

public class AppStateMain extends AbstractAppState {
	private VBox root;

	public AppStateMain(AppStateManager manager) {
		super(manager);
	}

	@Override
	public Scene createScene() {
		root = new VBox();
		root.setAlignment(Pos.TOP_CENTER);

		scene = new Scene(root, DFConsts.SCREEN_X, DFConsts.SCREEN_Y, true);
		scene.setFill(Color.WHITE);

		// Titel
		Text txt = new Text("Defenders FX");
		txt.setFont(new Font(30));
		root.getChildren().add(txt);

		createPlayField();

		return scene;
	}

	private void createPlayField() {
		PlayField playfield = new ExamplePlayField();

		Group rootField = new Group();
		root.getChildren().add(rootField);

		Field[][] fields = playfield.getFields();

		for (int i = 0; i < playfield.getWidth(); i++) {
			for (int j = 0; j < playfield.getHeight(); j++) {
				Field field = fields[i][j];

				Shape cell = field.getShape();

				cell.setTranslateX(i * field.getWidth());
				cell.setTranslateY(j * field.getHeight());
				rootField.getChildren().add(cell);
			}
		}
	}

	@Override
	public void activate() {
		// any key switches to exit
		scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
			public void handle(KeyEvent event) {
				AppStates state = AppStates.EXIT;
				if (event.getCode() == KeyCode.BACK_SPACE) {
					state = AppStates.MENU;
				}
				manager.switchTo(state);
			}
		});
	}

	@Override
	public void exit() {
		scene.setOnKeyPressed(null);
	}

	@Override
	public void init() {
		super.init();
	}
}
